import { RefObject, useState, useEffect } from 'react'
import { AutoComplete, FormInstance, message } from 'antd'
import _ from 'lodash'
import { awaitWrap } from '@js/tool'
import { getInfoListByName, getDataByFullName } from '../partyModal/ajax'
import style from './index.module.less'
import { NameSearchSchema } from '@components/schema/nameSearch'
import { DictionaryItem } from '@js/dictionary';
const { Option } = AutoComplete

// 改变名称
async function changeName (name: string, type: string, setLoading: (v: boolean) => void, setInfoList: (v: NameSearchSchema[]) => void) {
  setInfoList([])
  if (name) {
    setLoading(true)
    const [e, data] = await awaitWrap(getInfoListByName(name, type))
    setLoading(false)
    if (e) {
      return message.warning(e.message, 2)
    }
    setInfoList(data)
  }
}

const searchHandle = _.debounce(changeName, 600) // 缓动

// 格式化企业数据
function formatData (data: { [k: string]: any } = {}, typeList: DictionaryItem[]): { [k: string]: any } {
  if (data.tag) {
    try {
      data.tag = JSON.parse(data.tag)
      data.subject_type_tag = data.tag.subject_type_tag
      data.subject_type = (typeList[data.subject_type_tag] || {}).value
    } catch (e) {
      data.tag = {}
    }
  }
  if (!['本地', '外地', '港', '澳', '台', '外国'].includes(data.area)) {
    delete data.area
  }
  return data
}

// 选择当事人信息
async function selectPersonInfo (
  formRef: RefObject<FormInstance>,
  data: { [k: string]: any },
  index: number,
  type: string,
  typeList: DictionaryItem[],
  infoList: NameSearchSchema[],
  setInfoList: (v: NameSearchSchema[]) => void) {
  const c = formRef.current
  if (!data.address) {
    const hide = message.loading('加载中', 120)
    const [e, d] = await awaitWrap(getDataByFullName(data.name, type))
    const list = [...infoList]
    if (d) {
      list.splice(index, 1, d)
    }
    setInfoList(list)
    hide()
    if (e) {
      console.error(e)
      return message.warning(e.message, 2)
    }
    if (d) {
      data = d
    }
  }
  data = formatData(data, typeList)
  const keys = Object.keys(data)
  const map: { [k: string]: any } = {}
  keys.forEach(key => {
    map[key] = data[key] || ''
  })
  delete map.id
  c?.setFieldsValue(map)
}

interface Props {
  name: string
  formRef: RefObject<FormInstance>
  type: string
  typeList: DictionaryItem[]
  value?: string
  onChange?: () => void
}

function Main ({ name, formRef, type, typeList, value, onChange }: Props) {
  const [loading, setLoading] = useState(false)
  const [infoList, setInfoList] = useState<NameSearchSchema[]>([])
  const notice = <div>{loading ? '检索中' : '无匹配数据'}</div>
  return (
    <div>
      <AutoComplete value={value} placeholder={`请输入${name}`} onSearch={v => searchHandle(v, type, setLoading, setInfoList)} onChange={onChange} notFoundContent={notice}>
        {infoList.map((li, i) => {
          return (
            <Option key={i} value={li.name}>
              <div className={style.option} onClick={() => selectPersonInfo(formRef, li, i, type, typeList, infoList, setInfoList)}>{`${li.name}（证件号：${li.license || '无'}）`}</div>
            </Option>
          )
        })}
      </AutoComplete>
    </div>
  )
}

export default Main
